package test.task;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.Properties;

public class TaskFactory {
	/**
	 * 处理器组件配置对象
	 */
	private Properties properties = new Properties();

	/**
	 * 单态工厂实例
	 */
	private static TaskFactory m_instance = null;

	/**
	 * 工厂构造函数，用于加载处理器组件配置文件
	 * 
	 * @throws TaskException
	 */
	public TaskFactory() throws TaskException {
		String filename = "tasks.properties";
		try {
			InputStream in = getClass().getResourceAsStream(filename);
			this.properties.load(in);
		} catch (FileNotFoundException e) {
			throw TaskException.fileNotFound(filename);
		} catch (IOException e) {
			throw TaskException.loadPropFileFailed(filename);
		}
	}

	/**
	 * 创建工厂的唯一实例
	 * 
	 * @return
	 * @throws TaskException
	 */
	public static TaskFactory getInstance() throws TaskException {
		if (m_instance == null)
			m_instance = new TaskFactory();
		return m_instance;
	}

	/**
	 * 根据用户请求的地址，取得处理器对象
	 * 
	 * @param cmd
	 * @return
	 * @throws TaskException
	 */
	public ITask getTask(String taskType) throws TaskException {
		return createTask(taskType);
	}

	/**
	 * 根据用户请求的地址，创建处理器对象
	 * 
	 * @param cmd
	 * @return
	 * @throws TaskException
	 */
	public ITask createTask(String taskType) throws TaskException {
		ITask task = null;

		// 取得处理器类名
		String handlerName = this.properties.getProperty(String
				.valueOf(taskType));

		// 未配置实现类
		if (handlerName == null) {
			throw TaskException.taskNotFound(String.valueOf(taskType));
		}

		// 未找到实现类
		try {
			// 加载类的实例
			Class<?> cls = Class.forName(handlerName);
			Constructor<?> ct = cls.getConstructor();
			task = (ITask) ct.newInstance();
		} catch (Exception e) {
			throw TaskException.taskNotFound(e.getMessage());
		}
		
		return task;
	}
}
